﻿using NoteSystem.Utils;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace NoteSystem
{
    public partial class User : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                if (Session["User"]!=null)
                {
                    InitUser();
                }
            }
            
        }
        public void InitUser()
        {
            DataSet ds = DbHelper.Query("select * from users ");
            //把容器给Repeater
            rptnUser.DataSource= ds;
            rptnUser.DataBind();
        }

        protected void rptnUser_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            int id = Convert.ToInt32(e.CommandArgument);
            DataSet ds = DbHelper.Query("select manager from users where id="+id);
            if (Convert.ToInt32(ds.Tables[0].Rows[0]["manager"])==0)
            {
                int flag = DbHelper.ExecuteSql($"delete from users where id={id}");
                if (flag>0)
                {
                    Response.Write("<script>alert('删除成功')</script>");
                    InitUser();
                }
            }
            else
            {
                Response.Write("<script>alert('禁止删管理员')</script>");
            }

        }

        protected void btnDelete_Click(object sender, EventArgs e)
        {
            #region 全选删除
            int sign = 0;
            //遍历所有的数据行
            for (int i = 0; i < rptnUser.Items.Count; i++)
            {
                //获取每一行的勾选框
                CheckBox cbx = rptnUser.Items[i].FindControl("cbxItem") as CheckBox;
                int userId = Convert.ToInt32((rptnUser.Items[i].FindControl("hfUserId") as HiddenField).Value);
                //判断勾选框是否勾选
                if (cbx.Checked==true)
                {
                    DataSet ds = DbHelper.Query("select manager from users where id="+userId);
                    if (Convert.ToInt32(ds.Tables[0].Rows[0]["manager"])==0)
                    {
                        int flag = DbHelper.ExecuteSql("delete from users where id=" + userId);
                        if (flag > 0)
                        {
                            sign++;
                        }
                    }
                    else
                    {
                        Response.Write("<script>alert('禁止删管理员')</script>");
                    }

                }
            }
            if (sign > 0)
                Response.Write($"<script>alert('删除成功，共删除{sign}条')</script>");
            InitUser();
            #endregion
        }
    }
}